package com.adulcimer.core.filter;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.adulcimer.core.common.RequestWrapper;
import com.adulcimer.models.entity.domain.User;
import com.adulcimer.models.entity.service.UserService;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;


import java.io.IOException;

/**
 * @author Simon
 * @create 2025/2/21
 * @Description 登录拦截器，count+1
 **/

@WebFilter(filterName = "LoginFilter",urlPatterns = "/api/account/login")
public class LoginFilter implements Filter {

    private final UserService userService;

    public LoginFilter(UserService userService) {
        this.userService = userService;
    }

    @Override
    public void init(FilterConfig filterConfig) {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        RequestWrapper requestWrapper = new RequestWrapper(request);
        String contentType = request.getContentType();

        //判断请求类型
        if (contentType == null) { //表单请求
            filterChain.doFilter(request, response);
            return;
        } else if (contentType.startsWith("multipart/")) { //文件上传类型
            filterChain.doFilter(request, response);
            return;
        } else if (contentType.startsWith("application/json")) {//json请求
            //先进接口
            filterChain.doFilter(requestWrapper, response);
            String bodyString = requestWrapper.getBodyString();
            JSONObject jsonObject = JSONUtil.parseObj(bodyString);
            String account = jsonObject.getStr("account");
            User eq = userService.lambdaQuery().eq(User::getAccount, account).one();
            eq.setCount(eq.getCount() + 1);
            userService.updateById(eq);
        }
    }

    @Override
    public void destroy() {
        // 清理资源
    }
}
